﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BasicForms;
using GeneralLibs;
using Lists;
using System.Collections;
using Excel = Microsoft.Office.Interop.Excel;

namespace ListForms.NhaCungUng
{
    public partial class FrmDanhSachNhaCungUng : BasicForms.FrmSupportPrintableComponents
    {
        public FrmDanhSachNhaCungUng()
        {
            InitializeComponent();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                switch (keyData)
                {
                    //case Keys.F2:
                    //    btnCreateNew_Click(null, null);
                    //    break;
                    //case Keys.F3:
                    //case Keys.Enter:
                    //    btnSaveLedger_Click(null, null);
                    //    break;
                    //case Keys.F5:
                    //    DanhMucNhaCungUng.Instance.LoadFromDB();
                    //    break;
                    //case Keys.F8:
                    case Keys.Delete:
                        Delete();
                        break;
                    default:
                        return base.ProcessCmdKey(ref msg, keyData);
                        break;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        public EditState _EditState = EditState.Undefined;

        protected void SetEditState(EditState editState)
        {
            try
            {
                _EditState = editState;

                base.SetEditState(editState);
                switch (editState)
                {
                    case EditState.Modifying:
                        gridViewDs.OptionsBehavior.Editable = true;
                        btnCreateNew.Enabled = false;
                        btnClose.Enabled = false;
                        btnSaveLedger.Enabled = true;
                        break;
                    case EditState.SavedInLedger:
                        gridViewDs.OptionsBehavior.Editable = false;
                        btnCreateNew.Enabled = true;
                        btnClose.Enabled = true;
                        btnSaveLedger.Enabled = false;
                        break;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private DataTable _GridDataSouce
        {
            get
            {
                if (gridControlDs.DataSource is DataTable)
                    return gridControlDs.DataSource as DataTable;
                if (gridControlDs.DataSource is DataView)
                    return (gridControlDs.DataSource as DataView).ToTable();
                else return null;
            }
        }

        private void FrmDanhSachNhaCungUng_Load(object sender, EventArgs e)
        {
            try
            {
                DanhMucNhaCungUng.Instance.LoadFromDB();
                gridControlDs.DataSource = DanhMucNhaCungUng.Instance.DataTable;
                FormatNumberInGridView(gridViewDs);
                _GridDataSouce.AcceptChanges();
                SetEditState(EditState.SavedInLedger);
                foreach (DataRow row in _GridDataSouce.Rows)
                {
                    if (row.RowState == DataRowState.Added)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnCreateNew_Click(object sender, EventArgs e)
        {
            try
            {
                SetEditState(EditState.Modifying);
                gridViewDs.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
                _GridDataSouce.AcceptChanges();
                foreach (DataRow row in _GridDataSouce.Rows)
                {
                    if (row.RowState == DataRowState.Added)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnSaveLedger_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
                SetEditState(EditState.SavedInLedger);
                gridViewDs.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;
                _GridDataSouce.AcceptChanges();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void Save()
        {
            try
            {
                foreach (DataRow row in _GridDataSouce.Rows)
                {
                    if (row.RowState == DataRowState.Added)
                    {
                        Lists.NhaCungUng nhaCungUngNew = DanhMucNhaCungUng.Instance.NewDoiTuong();
                        if (row["TenCongTy"] is string)
                            nhaCungUngNew.TenCongTy = row["TenCongTy"].ToString();
                        if (row["TenNguoiLienHe"] is string)
                            nhaCungUngNew.TenNguoiLienHe = row["TenNguoiLienHe"].ToString();
                        if (row["SDT"] is string)
                            nhaCungUngNew.SDT = row["SDT"].ToString();
                        if (row["TenThuoc"] is string)
                            nhaCungUngNew.TenThuoc = row["TenThuoc"].ToString();
                        if (row["GhiChu"] is string)
                            nhaCungUngNew.GhiChu = row["GhiChu"].ToString();
                        if (row["DonGia"] is decimal)
                            nhaCungUngNew.DonGia = Convert.ToDecimal(row["DonGia"].ToString());
                        if (row["PhanTramChietKhau"] is decimal)
                            nhaCungUngNew.PhanTramChietKhau = Convert.ToDecimal(row["PhanTramChietKhau"].ToString());
                        nhaCungUngNew.NgayNhap = CommonLib.GetSystemDateTime();

                        nhaCungUngNew.InsertToDBTrucTiep();
                    }
                    else if (row.RowState == DataRowState.Modified)
                    {
                        Lists.NhaCungUng nhaCungUng = DanhMucNhaCungUng.Instance.GetByID((Guid)row["ID"]);
                        if (nhaCungUng == null)
                        {
                            //Insert
                        }
                        else
                        {
                            if (row["TenCongTy"] is string)
                                nhaCungUng.TenCongTy = row["TenCongTy"].ToString();
                            if (row["TenNguoiLienHe"] is string)
                                nhaCungUng.TenNguoiLienHe = row["TenNguoiLienHe"].ToString();
                            if (row["SDT"] is string)
                                nhaCungUng.SDT = row["SDT"].ToString();
                            if (row["TenThuoc"] is string)
                                nhaCungUng.TenThuoc = row["TenThuoc"].ToString();
                            if (row["GhiChu"] is string)
                                nhaCungUng.GhiChu = row["GhiChu"].ToString();
                            if (row["DonGia"] is decimal)
                                nhaCungUng.DonGia = Convert.ToDecimal(row["DonGia"].ToString());
                            if (row["PhanTramChietKhau"] is decimal)
                                nhaCungUng.PhanTramChietKhau = Convert.ToDecimal(row["PhanTramChietKhau"].ToString());

                            nhaCungUng.UpdateToDB();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void Delete()
        {
            try
            {
                ArrayList arDeletedChungTu = new ArrayList();
                foreach (int index in gridViewDs.GetSelectedRows())
                {
                    try
                    {
                        if (index >= 0)
                            arDeletedChungTu.Add(DanhMucNhaCungUng.Instance.GetByID((Guid)gridViewDs.GetDataRow(index)["ID"]));
                    }
                    catch (Exception ex)
                    {
                    }
                }

                foreach (Lists.NhaCungUng ncu in arDeletedChungTu)
                {
                    if (ncu == null) return;
                    if (MessageBox.Show("Bạn có chắc chắn xóa bản ghi này", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        gridViewDs.BeginUpdate();
                        ncu.DeleteFromDB();
                        gridViewDs.EndUpdate();
                    }
                }

            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                FrmProgressBarDev.FinishShowProgress();
            }
        }
        protected void ImportFromExcel()
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Excel file|*.xlsx;*.xls";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    DataTable dtError = DanhMucNhaCungUng.Instance.DataTable.Clone();

                    string path = openFileDialog.FileName;
                    Excel.ApplicationClass app = new Microsoft.Office.Interop.Excel.ApplicationClass();
                    Excel.Workbook workBook = app.Workbooks.Open(path, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t",
                                    false, false, 0, true, 1, 0);
                    Excel.Worksheet workSheet = (Excel.Worksheet)workBook.ActiveSheet;
                    Excel.Range range = workSheet.UsedRange;

                    BasicForms.FrmProgressBarDev.StartShowProgress();
                    if (range.Columns.Count >= 3)
                    {
                        Hashtable htHangKhongHople = new Hashtable();
                        int countDaXuLy = 1;
                        int countDongTrang = 0;

                        dtError.Clear();

                        for (int rowIndex = 2; rowIndex <= range.Rows.Count; rowIndex++)
                        {
                            string tenCongTy = "";
                            string tenNguoiLienHe = "";
                            string SDT = "";
                            string tenThuoc = "";
                            decimal donGia = 0;
                            decimal phanTramChietKhau = 0;
                            string ghiChu = "";
                            DateTime? ngayNhap = null;

                            #region Doc tu excel vao bien
                            try
                            {
                                tenCongTy = (range.Cells[rowIndex, 2] as Excel.Range).Text.ToString().Trim();
                            }
                            catch (Exception ex)
                            {
                            }
                            try
                            {
                                tenNguoiLienHe = (range.Cells[rowIndex, 3] as Excel.Range).Value2.ToString().Trim();
                            }
                            catch (Exception ex)
                            {
                            }
                            try
                            {
                                SDT = (range.Cells[rowIndex, 4] as Excel.Range).Value2.ToString().Trim();
                            }
                            catch (Exception ex)
                            {
                            }
                            try
                            {
                                donGia = decimal.Parse((range.Cells[rowIndex, 5] as Excel.Range).Value2.ToString().Trim());
                            }
                            catch (Exception ex)
                            {
                            }
                            try
                            {
                                phanTramChietKhau = decimal.Parse((range.Cells[rowIndex, 6] as Excel.Range).Value2.ToString().Trim());
                            }
                            catch (Exception ex)
                            {
                            }
                            try
                            {
                                ghiChu = (range.Cells[rowIndex, 7] as Excel.Range).Value2.ToString().Trim();
                            }
                            catch (Exception ex)
                            {
                            }
                            try
                            {
                                ngayNhap = DateTime.Parse((range.Cells[rowIndex, 8] as Excel.Range).Value2.ToString().Trim());
                            }
                            catch (Exception ex)
                            {
                            }

                            #endregion

                            Lists.NhaCungUng nhaCungUng = null;
                            if (countDongTrang > 20)  //Tranh truong hop doc hang nghin dong trang k can thiet
                            {
                                if (MessageBox.Show("Bạn có muốn dừng đọc file excel do quá 20 dòng không có dữ liệu? ", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                                {
                                    break;
                                }
                                else
                                {
                                    try
                                    {
                                        nhaCungUng = Lists.DanhMucNhaCungUng.Instance.GetByProperty("Ma", tenCongTy);

                                        if (nhaCungUng == null)
                                        {
                                            if (tenCongTy != "")
                                            {
                                                //Thêm thuốc mới với mã trong excel
                                                nhaCungUng = Lists.DanhMucNhaCungUng.Instance.NewDoiTuong();
                                                nhaCungUng.TenCongTy = tenCongTy;
                                                nhaCungUng.TenNguoiLienHe = tenNguoiLienHe;
                                                nhaCungUng.SDT = SDT;
                                                nhaCungUng.TenThuoc = tenThuoc;
                                                nhaCungUng.DonGia = donGia;
                                                nhaCungUng.PhanTramChietKhau = phanTramChietKhau;
                                                nhaCungUng.GhiChu = ghiChu;
                                                if (ngayNhap != null)
                                                    nhaCungUng.NgayNhap = ngayNhap;
                                                else
                                                    nhaCungUng.NgayNhap = CommonLib.GetSystemDateTime();

                                                nhaCungUng.InsertToDB();
                                            }
                                        }
                                        else
                                        {
                                            if (tenCongTy != "")
                                            {
                                                nhaCungUng.TenCongTy = tenCongTy;
                                                nhaCungUng.TenNguoiLienHe = tenNguoiLienHe;
                                                nhaCungUng.SDT = SDT;
                                                nhaCungUng.TenThuoc = tenThuoc;
                                                nhaCungUng.DonGia = donGia;
                                                nhaCungUng.PhanTramChietKhau = phanTramChietKhau;
                                                nhaCungUng.GhiChu = ghiChu;
                                                if (ngayNhap != null)
                                                    nhaCungUng.NgayNhap = ngayNhap;

                                                nhaCungUng.UpdateToDB();
                                            }
                                        }

                                        if (nhaCungUng == null && tenCongTy == "")
                                        {
                                            countDongTrang++;
                                        }

                                        BasicForms.FrmProgressBarDev.Status = "Đã xử lý " + countDaXuLy + " dòng";
                                        countDaXuLy++;
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBoxEx.Show(ex.Message, 5);
                                    }
                                }
                            }
                            else
                            {
                                try
                                {
                                    nhaCungUng = Lists.DanhMucNhaCungUng.Instance.GetByProperty("Ma", tenCongTy);

                                    if (nhaCungUng == null)
                                    {
                                        if (tenCongTy != "")
                                        {
                                            //Thêm thuốc mới với mã trong excel
                                            nhaCungUng = Lists.DanhMucNhaCungUng.Instance.NewDoiTuong();
                                            nhaCungUng.TenCongTy = tenCongTy;
                                            nhaCungUng.TenNguoiLienHe = tenNguoiLienHe;
                                            nhaCungUng.SDT = SDT;
                                            nhaCungUng.TenThuoc = tenThuoc;
                                            nhaCungUng.DonGia = donGia;
                                            nhaCungUng.PhanTramChietKhau = phanTramChietKhau;
                                            nhaCungUng.GhiChu = ghiChu;
                                            if (ngayNhap != null)
                                                nhaCungUng.NgayNhap = ngayNhap;
                                            else
                                                nhaCungUng.NgayNhap = CommonLib.GetSystemDateTime();

                                            nhaCungUng.InsertToDB();
                                        }
                                    }
                                    else
                                    {
                                        nhaCungUng.TenCongTy = tenCongTy;
                                        nhaCungUng.TenNguoiLienHe = tenNguoiLienHe;
                                        nhaCungUng.SDT = SDT;
                                        nhaCungUng.TenThuoc = tenThuoc;
                                        nhaCungUng.DonGia = donGia;
                                        nhaCungUng.PhanTramChietKhau = phanTramChietKhau;
                                        nhaCungUng.GhiChu = ghiChu;
                                        if (ngayNhap != null)
                                            nhaCungUng.NgayNhap = ngayNhap;

                                        nhaCungUng.UpdateToDB();
                                    }

                                    if (nhaCungUng == null && tenCongTy == "")
                                    {
                                        countDongTrang++;
                                    }

                                    BasicForms.FrmProgressBarDev.Status = "Đã xử lý " + countDaXuLy + " dòng";
                                    countDaXuLy++;
                                }
                                catch (Exception ex)
                                {
                                    MessageBoxEx.Show(ex.Message, 5);
                                }

                                BasicForms.FrmProgressBarDev.Status = "Đã xử lý " + countDaXuLy + " dòng";
                                countDaXuLy++;
                            }
                        }
                    }
                    workBook.Close(false, path, true);
                    BasicForms.FrmProgressBarDev.FinishShowProgress();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                _GridDataSouce.AcceptChanges();
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                PrintWithHeader(true, gridControlDs, true, true, "Danh sách quản lý nhà cung ứng", "");
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnExportToExcel_Click(object sender, EventArgs e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnImportExcel_Click(object sender, EventArgs e)
        {
            try
            {
                ImportFromExcel();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void gridViewDs_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            try
            {
                DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                view.SetRowCellValue(e.RowHandle, view.Columns["NgayNhap"], DateTime.Today);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void FrmDanhSachNhaCungUng_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                foreach (DataRow row in _GridDataSouce.Rows)
                {
                    if (row.RowState == DataRowState.Added || row.RowState == DataRowState.Modified)
                    {
                        if (MessageBox.Show("Bạn chưa lưu các thay đổi. Bạn có muốn lưu lại không", "Thông báo", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        {
                            Save();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
    }
}